﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.Data;
using iMall.AtoZ.Helper;
using GemBox.ExcelLite;

namespace iMall.AtoZ.DoPost
{
    /// <summary>
    /// DoSaveOrder 的摘要说明
    /// </summary>
    public class DoSaveOrder : IHttpHandler
    {

        public void ProcessRequest ( HttpContext context )
        {
            string info = SaveData(context);
            context.Response.ContentType = "application/text";
            context.Response.Write(info);
        }

        private string SaveData ( HttpContext context )
        {
            string data = context.Request["data"];
            string re = "导入失败";
            if ( data == null )
            {
                return re;
            }

            int countRow = 0;
            int countData = 0;
            int okRow = 0;
            try
            {
                FileInfoEntity info = JsonConvert.DeserializeObject<FileInfoEntity>(data.Replace(@"\", @"\\"));
                if ( !System.IO.File.Exists(info.Path) )
                {
                    return re;
                }
                List<string> tables = GemBoxExcelLiteHelper.GetExcelSheetNames(info.Path);

                //TemplateEntity.InitList();
                IDAL<OrderInfoEnity> dal = DALFactory.GetOrderInfoDAL();

                countRow = 0;
                countData = 0;
                okRow = 0;

                foreach ( string tbName in tables )
                {
                    DataSet ds = GemBoxExcelLiteHelper.LoadExcel(info.Path, tbName, HDRString.NO, "tb");
                    if ( ds.Tables.Count < 1 || ds.Tables["tb"].Rows.Count < 1 || ds.Tables["tb"].Columns.Count < 1 )
                    {
                        continue;
                    }

                    DataRow header = ds.Tables["tb"].Rows[0];
                    Dictionary<string, string> template = TemplateEntity.GetTemplate(header, info.Merchant);
                    if ( template.Count < 1 )
                    {
                        AtoZUtility.Logging.Error(string.Format("【{0}】【{1}】导入模板未找到", info.Path, tbName));
                        continue;
                    }

                    int impData = 0;

                    foreach ( KeyValuePair<string, string> kv in template )
                    {
                        if ( kv.Value == "OrderID" )
                        {
                            break;
                        }
                        impData++;
                    }

                    if ( impData > ds.Tables["tb"].Columns.Count )
                    {
                        impData = 0;
                    }

                    foreach ( DataRow dr in ds.Tables["tb"].Rows )
                    {
                        if ( dr[impData].ToString() == header[impData].ToString() || ( dr[impData] == null || dr[impData].ToString().Length < 1 ) )
                        {
                            continue;
                        }
                        countRow++;
                        OrderInfoEnity order = AtoZUtility.GetOrderInfoEnity(dr, header, template);

                        if ( order.OrderID.Length < 1 || order.Addr.Length < 1 )
                        {
                            if ( order.OrderID.Length > 1 )
                            {
                                LoggingEx(dr, header);
                            }
                            continue;
                        }
                        order.Merchant = info.Merchant;
                        order.BatchID = info.BatchNum.ToString();
                        order.FileName = info.Name;
                        okRow++;

                        if ( order.Product.Trim().Length < 1 || order.UserName.Length < 1 )
                        {
                            AtoZUtility.Logging.Info(string.Format("file【{0}】,orderid【{1}】", info.Path, order.OrderID));
                        }

                        OrderInfoEnity tmp = AtoZUtility.GetOrderInfoEntityByOrderID(order.OrderID, order.Merchant, template);
                        if ( tmp != null )
                        {
                            order.ID = tmp.ID;
                            dal.Upadte(order);
                        }
                        else
                        {
                            dal.Insert(order);
                        }

                        countData++;
                    }
                }

                string fileName = info.Path.Split('\\').Last<string>();
                IDAL<LoadTraceEntity> loadDal = DALFactory.GetLoadTraceDAL();
                loadDal.Insert(new LoadTraceEntity() { Path = info.Path, LoadOn = DateTime.Now, Total = countRow, Result = countData, FileName = fileName, LoadInfo = info.Merchant });

                if ( countData == 0 )
                {
                    AtoZUtility.Logging.Info(string.Format("file【{0}】", info.Path));
                }
                re = string.Format("<td class=\"reslutTD\">导入成功</td><td class=\"reslutTD\">{0}</td><td class=\"reslutTD\">{2}</td><td class=\"reslutTD\">{1}</td>", countData, countRow, okRow);
            }
            catch ( Exception ex )
            {
                AtoZUtility.Logging.Error(ex.ToString());
                re = string.Format("<td class=\"reslutTD\">导入失败</td><td class=\"reslutTD\">{0}</td><td class=\"reslutTD\">{2}</td><td class=\"reslutTD\">{1}</td>", countData, countRow, okRow);
            }


            return re;
        }

        private void LoggingEx ( DataRow dr, DataRow header )
        {
            string re = string.Empty;
            foreach ( DataColumn dc in dr.Table.Columns )
            {
                re += string.Format("{0}:{1}", header[dc.ColumnName], dr[dc.ColumnName]);
            }

            AtoZUtility.Logging.Warn(re);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}